package com.fjut.kms.tools;

import com.fjut.kms.exception.KMSException;
import org.dom4j.*;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.List;

/**
 * Created by Empathy on 2017/7/12.
 */
public class XmlManager {
    public  static String GetFirtElemntByTagName(String tagName,String xmlStr) throws DocumentException
    {
        Document doc = DocumentHelper.parseText(xmlStr); // 将字符串转为XML
        Element rootElt = doc.getRootElement(); // 获取根节点smsReport
        if (rootElt.element(tagName)==null)throw new KMSException("未找到名为"+tagName+"的节点");
        List<org.dom4j.Element> nl=rootElt.elements(tagName);
        return  nl.get(0).getTextTrim();

    }

    public  static org.dom4j.Document transformstrtoxml(String str) {
        try {
            StringReader read = new StringReader(str);
            //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
            InputSource source = new InputSource(read);

            ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes());
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            org.dom4j.Document document = reader.read(new InputStreamReader(input, "utf-8"));// 璁剧疆涓篻bk锛岄伩鍏嶄腑鏂囦贡鐮侀棶棰?

            if (document == null) {
                return (null);
            }
            StringReader reader1 = new StringReader(document.asXML());
            InputSource source1 = new InputSource(reader1);
            javax.xml.parsers.DocumentBuilderFactory documentBuilderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
            javax.xml.parsers.DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            return (Document) documentBuilder.parse(source);

        } catch (Exception e) {
            e.printStackTrace();
        }



        return null;
    }
    public static String buildLoginResultXml(){

        StringBuilder xml=new StringBuilder();
        xml.append("<?xml version=\"1.0\"?>");
        xml.append("<params>");
        xml.append("<CheckStatus>1</CheckStatus>");
        xml.append("</params>");
        /*String strXML=null;
        try{
            //创建新文档
            Document doc =  DocumentHelper.createDocument();
            Element root = doc.addElement("params");
            root.addElement("CheckStatus").addText("1");
            strXML=doc.toString();
            System.out.println(strXML);
        }catch (Exception e){
            e.printStackTrace();
        }*/
        return xml.toString();
    }

    public static  String buildXmlError(String strArg){
        StringBuilder xml=new StringBuilder();
        xml.append("<?xml version=\"1.0\"?>");
        xml.append("<params>");
        xml.append("<CheckStatus>0</CheckStatus>");
        xml.append("<errorMessage>"+strArg+"</errorMessage>");
        xml.append("</params>");
        return xml.toString();
    }
}
